package com.eop.managedBean;

import javax.faces.context.FacesContext;

import org.operamasks.faces.annotation.Accessible;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.form.impl.UICombo;
import org.operamasks.faces.user.util.Browser;

import com.base.common.provider.CommonKeySelectItemProvider;
import com.base.utils.IdUtils;
import com.eop.entity.EmergencyStage;
import com.eop.entity.Event;

@ManagedBean(name = "eop_addEmergencyStageBean", scope = ManagedBeanScope.REQUEST)
public class AddEmergencyStageBean extends BaseEmergencyStageBean {

	@Inject
	private FacesContext context;

	@Accessible
	@SaveState
	private String eventId = FacesContext.getCurrentInstance()
			.getExternalContext().getRequestParameterMap().get("eventId");

	@Bind(id = "Stage_B", attribute = "binding")
	private UICombo Stage_B_binding;

	@Bind(id = "Stage_S", attribute = "binding")
	private UICombo Stage_S_binding;
	@SaveState
	private String first;

	@Action(id = "Stage_B", event = "onselect", immediate = true)
	public void changeStageType() {
		first = Stage_B_binding.getSubmittedValue().toString().trim();
		Stage_S_items = CommonKeySelectItemProvider.getDirectCommonKey(first,
				false);
		Stage_S = null;
		Stage_S_binding.resetValue();
		Stage_S_binding.repaint();
	}

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			id = context.getExternalContext().getRequestParameterMap()
					.get("id");
			if (id != null && !"".equals(id)) {
				es = ecyService.getStageById(id);
				if (es != null) {
					Stage_S_items = CommonKeySelectItemProvider
							.getDirectCommonKey(es.getStage_b(), false);
					this.getEcyStageProperty(es);
				}
			} else {
				id = IdUtils.getUUID();
			}
		}
	}

	@Action(id = "save")
	public void save() {
		if (id != null && !"".equals(id)) {
			es = ecyService.getStageById(id);
			if (es != null) {
				this.setEcyStageProperty();
				ecyService.saveStage(es);
			} else {
				es = new EmergencyStage();
				this.setEcyStageProperty();
				Event event = eventService.getEventById(eventId);
				if (event != null)
					es.setEsEvent(event);
				ecyService.saveStage(es);
			}
		}
		String script = "closeWindow('ecyStage_relation')";
		Browser.execClientScript("window.parent", script);
	}
}
